package servlet;

import model.Order;
import model.User;
import service.OrderService;
import utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/orderList")
public class OrderListServlet extends HttpServlet {
   private OrderService oService = new OrderService();

   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   }

   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      // 获得当前登录用户（非管理员）
      User u = (User) request.getSession().getAttribute("user");
      if (u == null) {
         response.sendRedirect("/index");
         return;
      }

      // 获得当前登录用户的所有订单
      List<Order> list = oService.selectAll(u.getId());
      request.setAttribute("orderList", list);

      // 返回List<Order> list的JSON字符串
      response.setContentType("application/json;charset=utf-8");
      response.getWriter().println(JsonUtils.objectToString(list));
   }
}
